package com.example.keli.ui.register;

import android.os.CountDownTimer;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.example.keli.MainActivity;
import com.example.keli.R;
import com.example.keli.api.HttpUtils;
import com.example.keli.api.RetrofitManager;
import com.example.keli.api.http.api.BaseResponse;
import com.example.keli.api.http.api.subscriber.SubscriberListener;
import com.example.keli.base.App;
import com.example.keli.base.AppConfig;
import com.example.keli.base.BaseActivity;
import com.example.keli.base.utils.MD5Util;
import com.example.keli.base.utils.SPUtils;
import com.example.keli.base.utils.ToastUtil;
import com.example.keli.base.widget.ClearEditText;
import com.flyco.roundview.RoundTextView;
import com.google.gson.Gson;
import com.tuo.customview.VerificationCodeView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginAndRegisterActivity extends BaseActivity {


    @BindView(R.id.register_account)
    TextView registerAccount;
    @BindView(R.id.password_login)
    TextView passwordLogin;
    @BindView(R.id.codeview)
    VerificationCodeView codeview;
    @BindView(R.id.time_count)
    TextView timeCount;
    @BindView(R.id.code_next)
    RoundTextView codeNext;
    @BindView(R.id.shangyibu)
    TextView shangyibu;
    @BindView(R.id.login_code_layout)
    CardView loginCodeLayout;
    @BindView(R.id.phone)
    ClearEditText phone;
    @BindView(R.id.phone_next)
    RoundTextView phoneNext;
    @BindView(R.id.login_phone_layout)
    CardView loginPhoneLayout;
    @BindView(R.id.account_phone)
    ClearEditText accountPhone;
    @BindView(R.id.account_password)
    ClearEditText accountPassword;
    @BindView(R.id.login)
    RoundTextView login;
    @BindView(R.id.password_login_layout)
    CardView passwordLoginLayout;
    @BindView(R.id.register_phone)
    ClearEditText registerPhone;
    @BindView(R.id.register_code)
    ClearEditText registerCode;
    @BindView(R.id.register_time_out)
    TextView registerTimeOut;
    @BindView(R.id.register_password)
    ClearEditText registerPassword;
    @BindView(R.id.register_button)
    RoundTextView registerButton;
    @BindView(R.id.register_layout)
    CardView registerLayout;

    private int viewState = 0;//0验证码登录第一步，手机号界面，1：验证码界面。2：密码登录。3：注册界面

    @Override
    protected int layoutId() {
        return R.layout.activity_login_register;
    }

    @Override
    protected void bindData() {
        EventBus.getDefault().register(this);
    }


    private void loadDatas() {
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(String close_login) {
    }

    @OnClick({R.id.register_account, R.id.password_login, R.id.time_count, R.id.code_next, R.id.shangyibu, R.id.phone_next, R.id.login, R.id.register_time_out, R.id.register_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.register_account:
                switch (viewState) {
                    case 0:
                    case 1:
                    case 2:
                        viewState = 3;
                        showLayout();
                        registerAccount.setText("已有账号");
                        passwordLogin.setText("验证码登录");
                        break;
                    case 3:
                        viewState = 2;
                        showLayout();
                        registerAccount.setText("注册账号");
                        passwordLogin.setText("验证码登录");
                        break;
                }
                break;
            case R.id.password_login:
                switch (viewState) {
                    case 0:
                    case 1:
                        passwordLogin.setText("验证码登录");
                        viewState = 2;
                        showLayout();
                        registerAccount.setText("注册账号");
                        break;
                    case 2:
                    case 3:
                        passwordLogin.setText("密码登录");
                        viewState = 0;
                        showLayout();
                        registerAccount.setText("注册账号");
                        break;
                }

                break;
            case R.id.time_count:
                sendMsg(phone.getText().toString(), "login");
                timeCount.setEnabled(false);
                break;
            case R.id.code_next:
                codeLogin();
                break;
            case R.id.shangyibu:
                if (null != mDownTimer) {
                    mDownTimer.cancel();
                }
                viewState = 0;
                showLayout();
                break;
            case R.id.phone_next:
                sendMsg(phone.getText().toString(), "login");
                break;
            case R.id.login:
                passwordLogin(accountPhone.getText().toString(),accountPassword.getText().toString());
                break;
            case R.id.register_time_out:
                sendMsg(registerPhone.getText().toString(), "registered");
                registerTimeOut.setEnabled(false);
                break;
            case R.id.register_button:
                registerAccount();
                break;
        }
    }

    private void showLayout() {
        switch (viewState) {
            case 0:
                loginPhoneLayout.setVisibility(View.VISIBLE);
                loginCodeLayout.setVisibility(View.GONE);
                passwordLoginLayout.setVisibility(View.GONE);
                registerLayout.setVisibility(View.GONE);
                break;
            case 1:
                loginPhoneLayout.setVisibility(View.GONE);
                loginCodeLayout.setVisibility(View.VISIBLE);
                passwordLoginLayout.setVisibility(View.GONE);
                registerLayout.setVisibility(View.GONE);
                break;
            case 2:
                loginPhoneLayout.setVisibility(View.GONE);
                loginCodeLayout.setVisibility(View.GONE);
                passwordLoginLayout.setVisibility(View.VISIBLE);
                registerLayout.setVisibility(View.GONE);
                break;
            case 3:
                loginPhoneLayout.setVisibility(View.GONE);
                loginCodeLayout.setVisibility(View.GONE);
                passwordLoginLayout.setVisibility(View.GONE);
                registerLayout.setVisibility(View.VISIBLE);
                break;
        }
    }


    //验证码登录
    private void codeLogin() {
        if(TextUtils.isEmpty(phone.getText().toString())||TextUtils.isEmpty(codeview.getInputContent())){
            toast("账号验证码不能为空");
            return;
        }
        startProgressDialog();
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone.getText().toString());
        map.put("by_convey_code", "registered");
        map.put("code", codeview.getInputContent());
        HttpUtils.ApiFunc(RetrofitManager.mApiService.login(map), new SubscriberListener<BaseResponse<LoginData>>() {
            @Override
            public void onSuccess(BaseResponse<LoginData> rewardListBaseResponse) {
                stopProgressDialog();
                Gson gson = new Gson();
                //保存登录数据。下次不需要登录
                App.setAccount(rewardListBaseResponse.getData());
                SPUtils.put(LoginAndRegisterActivity.this, AppConfig.PERSONAL_DATA, gson.toJson(rewardListBaseResponse.getData()));
                MainActivity.start(LoginAndRegisterActivity.this);
                EventBus.getDefault().post(AppConfig.CLOSE_LOGIN);
                finish();
            }

            @Override
            public void onFailer(String msg) {
                stopProgressDialog();
                ToastUtil.show(msg);
            }

            @Override
            public void onTokenError() {

            }
        });
    }

    //账号密码登录
    private void passwordLogin(String phone,String password) {
        if(TextUtils.isEmpty(phone)||TextUtils.isEmpty(password)){
            toast("账号密码不能为空");
            return;
        }
        if(password.length()<8||password.length()>16){
            toast("密码不能小于8位大于16位");
            return;
        }
        startProgressDialog();
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("password", MD5Util.MD5(password));
        HttpUtils.ApiFunc(RetrofitManager.mApiFunc.login_a(map), new SubscriberListener<BaseResponse<LoginData>>() {
            @Override
            public void onSuccess(BaseResponse<LoginData> rewardListBaseResponse) {
                stopProgressDialog();
                Gson gson = new Gson();
                //保存登录数据。下次不需要登录
                App.setAccount(rewardListBaseResponse.getData());
                SPUtils.put(LoginAndRegisterActivity.this, AppConfig.PERSONAL_DATA, gson.toJson(rewardListBaseResponse.getData()));
                MainActivity.start(LoginAndRegisterActivity.this);
                finish();
            }

            @Override
            public void onFailer(String msg) {
                stopProgressDialog();
                ToastUtil.show(msg);
            }

            @Override
            public void onTokenError() {

            }
        });
    }

    //注册账号密码
    private void registerAccount() {
        if(TextUtils.isEmpty(registerPhone.getText().toString())||TextUtils.isEmpty(registerCode.getText().toString())||TextUtils.isEmpty(registerPassword.getText().toString())){
            toast("账号，验证码，密码均不能为空");
            return;
        }
        if(registerPassword.getText().toString().length()<8||registerPassword.getText().toString().length()>16){
            toast("密码不能小于8位大于16位");
            return;
        }
        startProgressDialog();
        Map<String, String> map = new HashMap<>();
        map.put("phone", registerPhone.getText().toString());
        map.put("password", MD5Util.MD5(registerPassword.getText().toString()));
        map.put("code", registerCode.getText().toString());
        map.put("by_convey_code", "registered");
        HttpUtils.ApiFunc(RetrofitManager.mApiFunc.registered(map), new SubscriberListener<BaseResponse<Object>>() {
            @Override
            public void onSuccess(BaseResponse<Object> rewardListBaseResponse) {
                stopProgressDialog();

                passwordLogin(registerPhone.getText().toString(),registerPassword.getText().toString());
//                Gson gson = new Gson();
//                //保存登录数据。下次不需要登录
//                App.setAccount(rewardListBaseResponse.getData());
//                SPUtils.put(LoginAndRegisterActivity.this, AppConfig.PERSONAL_DATA, gson.toJson(rewardListBaseResponse.getData()));
//                MainActivity.start(LoginAndRegisterActivity.this);
//                EventBus.getDefault().post(AppConfig.CLOSE_LOGIN);
//                finish();
            }

            @Override
            public void onFailer(String msg) {
                stopProgressDialog();
                ToastUtil.show(msg);
            }

            @Override
            public void onTokenError() {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (null != mDownTimer) {
            mDownTimer.cancel();
        }
    }

    private CountDownTimer mDownTimer;
    private final long OFFEST = 1000;
    private final long COUNT_DOWN = 60 * 1000;
    String mLeftTip = "";

    private void startCountDown() {
        mLeftTip = getString(R.string.account_check_code_left_tip);
        mDownTimer = new CountDownTimer(COUNT_DOWN, OFFEST) {
            @Override
            public void onTick(long millisUntilFinished) {
                timeCount.setText(String.format(mLeftTip, millisUntilFinished / OFFEST));
            }

            @Override
            public void onFinish() {
                timeCount.setEnabled(true);
                timeCount.setText("没收到验证码？重发一次");
            }
        };
        mDownTimer.start();
    }

    private void startRegisterCountDown() {
        mLeftTip = getString(R.string.account_check_code_left_tip);
        mDownTimer = new CountDownTimer(COUNT_DOWN, OFFEST) {
            @Override
            public void onTick(long millisUntilFinished) {
                registerTimeOut.setText(String.format(mLeftTip, millisUntilFinished / OFFEST));
            }

            @Override
            public void onFinish() {
                registerTimeOut.setEnabled(true);
                registerTimeOut.setText("重发一次");
            }
        };
        mDownTimer.start();
    }

    private void sendMsg(String phone, String type) {
        if(TextUtils.isEmpty(phone)){
            toast("手机号不能为空");
            return;
        }
        startProgressDialog();
        Map<String, String> map = new HashMap<>();
        map.put("address", phone);
        map.put("type", type);
        HttpUtils.ApiFunc(RetrofitManager.mApiService.sendSms(map), new SubscriberListener<BaseResponse<Object>>() {
            @Override
            public void onSuccess(BaseResponse<Object> rewardListBaseResponse) {
                stopProgressDialog();
                switch (type) {
                    case "login":
                        startCountDown();
                        viewState = 1;
                        showLayout();
                        break;
                    case "registered":
                        startRegisterCountDown();
                        break;
                }
            }

            @Override
            public void onFailer(String msg) {
                stopProgressDialog();
                ToastUtil.show(msg);
            }

            @Override
            public void onTokenError() {

            }
        });
    }
}
